package com.cwf.quality.common.strategy.analyzer;

import com.cwf.quality.common.enums.DataAnalyzerEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.dataanalyze.param.AnalyzerParamInfo;
import com.cwf.quality.model.dto.dataanalyze.result.ValueDistributionAnalyzeResult;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValueDistributionDataAnalyzer implements IDataAnalyzer {

    /**
     * 数值分布分析
     *
     * @param analyzerParamInfo
     * @return
     */
    @Override
    public QualityResultInfo<ValueDistributionAnalyzeResult> analyzeData(AnalyzerParamInfo analyzerParamInfo) {
        SqlUtils sqlUtils = analyzerParamInfo.getSqlUtils();

        ValueDistributionAnalyzeResult valueDistributionAnalyzeResult = new ValueDistributionAnalyzeResult();
        Map<String, List<ValueDistributionAnalyzeResult.ColumnValueCount>> columnValueCountMap = new HashMap<>();

        List<String> columnNameList = analyzerParamInfo.getColumnNameList();
        for (String columnName : columnNameList) {
            String sql = DataAnalyzerEnum.VALUE_DISTRIBUTION_ANALYZE.getSql()
                    .replace("{table}", analyzerParamInfo.getTableName())
                    .replace("{column}", columnName);

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, -1);


            List<ValueDistributionAnalyzeResult.ColumnValueCount> columnValueCountList = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                Object columnValue = map.get(columnName);
                Long count = (Long) map.get("count");
                columnValueCountList.add(new ValueDistributionAnalyzeResult.ColumnValueCount(columnValue, count));
            }
            columnValueCountMap.put(columnName, columnValueCountList);

        }
        valueDistributionAnalyzeResult.setColumnValueCountMap(columnValueCountMap);
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(valueDistributionAnalyzeResult)
                .build();
        return qualityResultInfo;
    }
}
